﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Management;

namespace BizTalkOneService
{
    class HostThrottleStatus
    {
        private List<PerformanceCounter> perfCountList = new List<PerformanceCounter>();
        EventLog appLog = new EventLog();

        public HostThrottleStatus()
        {
            List<string> lines = new List<string>();
            EnumerationOptions enumOptions = new EnumerationOptions();
            enumOptions.ReturnImmediately = false;
            ManagementObjectSearcher searchObject = new ManagementObjectSearcher("root\\MicrosoftBizTalkServer", "Select * from MSBTS_HostInstance where HostType=1 and ServiceState=4", enumOptions);

            try
            {
                foreach (ManagementObject inst in searchObject.Get())
                {
                    lines = inst["Name"].ToString().Substring(25).Split(' ').ToList();
                    perfCountList.Add(new PerformanceCounter("BizTalk:Message Agent", "Message publishing throttling state", lines[0], lines[1]));
                    perfCountList.Add(new PerformanceCounter("BizTalk:Message Agent", "Message delivery throttling state", lines[0], lines[1]));
                }

            }
            catch (Exception ex)
            {
                appLog.Source = Settings.EventLogSource;
                EventLogEntryType eventType = EventLogEntryType.Error;
                appLog.WriteEntry("Error retrieving host performance counters: " + ex.Message.ToString() + "\n" + ex.StackTrace, eventType); 
                
            }
        }


        public List<Counter> getStatus() 
        {
            List<Counter> l = new List<Counter>();
            foreach (PerformanceCounter p in perfCountList)
            {
                try
                {
                    if (p.NextValue() != 0)
                        l.Add(new Counter { CounterCategory="Throttle",  CounterName = p.InstanceName, CounterValue = Convert.ToInt32(p.NextValue()), ServerName = p.MachineName  });
                }
                catch (Exception ex)
                {
                    appLog.Source = Settings.EventLogSource;
                    EventLogEntryType eventType = EventLogEntryType.Error;
                    appLog.WriteEntry("Error adding host status to list: " + ex.Message.ToString() + "\n" + ex.StackTrace, eventType); 
                }
            }
            return l;
        }

     }
}
